import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:kudos/config/widget_config.dart';
import 'package:kudos/core/utils/kudo_helper.dart';
import '../../utils/kudo_colors.dart';
import '../../utils/image_resource_helper.dart';
import '../../widget/login_required_dialog.dart';
import '../../widget/report_dialog.dart';
import '../../state/person/persona_session_controller.dart';
import '../../state/topic/kite_topic_entity.dart';
import '../../state/topic/kite_topic_controller.dart';
import '../../state/topic/kite_topic_discussion_entity.dart';

class KiteTopicDetailScreen extends StatefulWidget {
  final KiteTopicEntity topic;

  const KiteTopicDetailScreen({super.key, required this.topic});

  @override
  State<KiteTopicDetailScreen> createState() => _KiteTopicDetailScreenState();
}

class _KiteTopicDetailScreenState extends State<KiteTopicDetailScreen> {
  late TextEditingController _bottomInputController;

  @override
  void initState() {
    super.initState();
    _bottomInputController = TextEditingController();
  }

  @override
  void dispose() {
    _bottomInputController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/main_background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: Stack(
          children: [
            Column(
              children: [
                _buildTopAppBar(),

                Expanded(
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        SizedBox(height: 16.h),

                        _buildTopicImage(),

                        SizedBox(height: 24.h),

                        _buildDiscussionList(),

                        SizedBox(height: 80.h),
                      ],
                    ),
                  ),
                ),
              ],
            ),

            Positioned(
              left: 0,
              right: 0,
              bottom: 0,
              child: _buildBottomInputButton(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTopAppBar() {
    return SafeArea(
      bottom: false,
      child: Container(
        height: 56.h,
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child: Row(
          children: [
            GestureDetector(
              onTap: () => Navigator.of(context).pop(),
              child:
                  Icon(
                    Icons.arrow_back_ios_new,
                    size: 22.sp,
                    color: Colors.black,
                  ).center(),
            ),

            SizedBox(width: 6.w),

            Expanded(
              child: Text(
                widget.topic.topicTextContent,
                style: GoogleFonts.lato(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w900,
                  color: Colors.black,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTopicImage() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: AspectRatio(
        aspectRatio: 343 / 140,
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(widget.topic.topicImageResource),
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildDiscussionList() {
    final discussions = KiteTopicController.globalInstance.getTopicDiscussions(
      widget.topic.uniqueIdentifier,
    );

    if (discussions.isEmpty) {
      return Container(
        padding: EdgeInsets.all(32.w),
        child: Text(
          'No discussions yet. Be the first to share your thoughts!',
          textAlign: TextAlign.center,
          style: GoogleFonts.lato(fontSize: 16.sp, color: KudoColors.grey),
        ),
      );
    }

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      decoration: BoxDecoration(
        color: KudoColors.green,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        children:
            discussions
                .map((discussion) => _buildDiscussionItem(discussion))
                .toList(),
      ),
    );
  }

  Widget _buildDiscussionItem(KiteTopicDiscussionEntity discussion) {
    final author = PersonaSessionController.quickGetUserById(
      discussion.publisherPersonaId,
    );

    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: KudoColors.green,
        borderRadius: BorderRadius.circular(16.r),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ImageResourceHelper.buildCircularAvatar(
            imagePath: author?.avatarResourceUrl ?? '',
            radius: 23.r,
          ),

          SizedBox(width: 12.w),

          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      author?.displayAlias ?? 'Unknown',
                      style: GoogleFonts.lato(
                        fontSize: 18.sp,
                        fontWeight: FontWeight.w900,
                        color: Colors.black,
                      ),
                    ),

                    const Spacer(),

                    _buildLikeButton(discussion),

                    SizedBox(width: 8.w),

                    _buildReportButton(discussion),
                  ],
                ),

                SizedBox(height: 8.h),
                Container(
                  padding: EdgeInsets.all(12.w),
                  decoration: ShapeDecoration(
                    color: KudoColors.inputBackground,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.only(
                        topRight: Radius.circular(24.r),
                        bottomLeft: Radius.circular(24.r),
                        bottomRight: Radius.circular(24.r),
                      ),
                    ),
                    shadows: [
                      BoxShadow(
                        color: Color(0xFF000300),
                        blurRadius: 0,
                        offset: Offset(0, 4),
                        spreadRadius: 0,
                      ),
                    ],
                  ),
                  child: Text(
                    discussion.discussionTextContent,
                    style: GoogleFonts.lato(
                      fontSize: 14.sp,
                      color: Colors.black,
                      height: 1.4,
                    ),
                  ),
                ).configWidget(borderRadius: 24.r),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildLikeButton(KiteTopicDiscussionEntity discussion) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    final isLiked =
        currentUser != null &&
        KiteTopicController.globalInstance
            .getDiscussionLikeStatus(discussion.uniqueIdentifier)
            .value;

    return GestureDetector(
      onTap: () => _handleLikeDiscussion(discussion),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          ImageResourceHelper.buildSvgIcon(
            svgPath: 'assets/svg/dianzan.svg',
            width: 20.w,
            height: 20.h,
            color: isLiked ? KudoColors.yellow : KudoColors.black,
          ),
          SizedBox(width: 4.w),
          Text(
            '${discussion.totalLikeCount}',
            style: GoogleFonts.lato(
              fontSize: 14.sp,
              fontWeight: FontWeight.w600,
              color: isLiked ? KudoColors.yellow : KudoColors.black,
            ),
          ),
          SizedBox(width: 8.w),
        ],
      ),
    );
  }

  Widget _buildReportButton(KiteTopicDiscussionEntity discussion) {
    return GestureDetector(
      onTap: () => _handleReportDiscussion(discussion),
      child: ImageResourceHelper.buildSvgIcon(
        svgPath: 'assets/svg/report.svg',
        width: 20.w,
        height: 20.h,
        color: KudoColors.black,
      ),
    );
  }

  Widget _buildBottomInputButton() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(color: Colors.transparent),
      child: Container(
        height: 50.h,
        decoration: BoxDecoration(
          color: KudoColors.yellow,
          borderRadius: BorderRadius.circular(24.r),
          border: Border.all(color: Colors.grey.shade300, width: 1),
        ),
        child: Row(
          children: [
            Expanded(
              child: TextField(
                controller: _bottomInputController,
                decoration: InputDecoration(
                  hintText: 'Start telling your story',
                  hintStyle: GoogleFonts.lato(
                    fontSize: 14.sp,
                    color: Colors.grey.shade500,
                  ),
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 20.w,
                    vertical: 12.h,
                  ),
                ),
                style: GoogleFonts.lato(fontSize: 14.sp, color: Colors.black),
                maxLines: 1,
              ),
            ),

            GestureDetector(
              onTap: _handleSendMessage,
              child: Container(
                width: 36.w,
                height: 36.h,
                margin: EdgeInsets.only(right: 6.w),
                decoration: BoxDecoration(
                  color: KudoColors.black,
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withValues(alpha: 0.2),
                      blurRadius: 2.r,
                      offset: Offset(0, 1.h),
                    ),
                  ],
                ),
                child:
                    ImageResourceHelper.buildSvgIcon(
                      svgPath: 'assets/svg/send.svg',
                      width: 20.w,
                      height: 20.w,
                      color: KudoColors.yellow,
                    ).center(),
              ),
            ),
          ],
        ),
      ).configWidget(borderRadius: 24.r),
    );
  }

  void _handleLikeDiscussion(KiteTopicDiscussionEntity discussion) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) {
      LoginRequiredDialog.show(
        context: context,
        title: 'Login Required',
        message: 'Please login to like discussions',
      );
      return;
    }

    final isLiked =
        KiteTopicController.globalInstance
            .getDiscussionLikeStatus(discussion.uniqueIdentifier)
            .value;

    bool success;
    if (isLiked) {
      success = KiteTopicController.globalInstance.unlikeDiscussion(
        discussion.uniqueIdentifier,
      );
    } else {
      success = KiteTopicController.globalInstance.likeDiscussion(
        discussion.uniqueIdentifier,
      );
    }

    if (success) {
      setState(() {});
    }
  }

  void _handleReportDiscussion(KiteTopicDiscussionEntity discussion) {
    ReportDialog.show(
      context: context,
      title: 'Report Discussion',
      onReport: (reportType) {
        final success = KiteTopicController.globalInstance
            .deleteTopicDiscussion(discussion.uniqueIdentifier);

        if (success) {
          KudoToast.showSuccessToast(context, 'Reported successfully');

          setState(() {});
        } else {
          KudoToast.showErrorToast(context, 'Report failed. Please try again.');
        }
      },
    );
  }

  void _handleSendMessage() {
    final content = _bottomInputController.text.trim();
    if (content.isEmpty) return;

    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) {
      LoginRequiredDialog.show(
        context: context,
        title: 'Login Required',
        message: 'Please login to share your story',
      );
      return;
    }

    _publishDiscussion(content);
    _bottomInputController.clear();
  }

  void _publishDiscussion(String content) {
    final success = KiteTopicController.globalInstance.publishTopicDiscussion(
      topicId: widget.topic.uniqueIdentifier,
      discussionContent: content,
    );

    if (success) {
      setState(() {});
    }
  }
}
